package com.example.androidproject.online;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.androidproject.MainActivity;
import com.example.androidproject.chat.pojo.ChatGroupInfo;
import com.example.androidproject.databinding.FragmentOnlineBinding;
import com.example.androidproject.online.activity.OnlineChatActivity;
import com.example.androidproject.online.adapter.OnlineAdapter;
import com.example.androidproject.sqlite.GroupRepository;
import com.example.androidproject.sqlite.UserRepository;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OnlineFragment extends Fragment {
    private static final String TAG = "OnlineFragment";
    private FragmentOnlineBinding binding;
    private static final int BROADCAST_PORT = 9876;
    private ArrayList<UserRepository.User> list = new ArrayList<>();
    private OnlineAdapter adapter;
    private String localIpAddress;
    private ExecutorService executorService;
    private UserRepository.User userClass;
    private final Gson gson = new Gson(); // Gson 实例化放在类成员中
    private GroupRepository groupRepository;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentOnlineBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        localIpAddress = getLocalIpAddress(binding.getRoot().getContext());
//        showToast(localIpAddress);
        executorService = Executors.newCachedThreadPool();
        groupRepository = new GroupRepository(this.getContext());

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        String userJson = sharedPreferences.getString("user", null);
        userClass = gson.fromJson(userJson, UserRepository.User.class);

        executorService.submit(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                sendBroadcast("FOUND");
                Log.e(TAG, "onCreateView: 发送一次");
                try {
                    Thread.sleep(1000); // 5 seconds interval
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        adapter = new OnlineAdapter(list, user -> {
            String json = gson.toJson(user);
            userClass = user;
            executorService.submit(() -> sendBroadcast(json));
        });

        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));
        return view;
    }

    private void sendBroadcast(String broadcastMessage) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255");
            byte[] message = broadcastMessage.getBytes();
            DatagramPacket packet = new DatagramPacket(message, message.length, broadcastAddress, BROADCAST_PORT);
            socket.send(packet);

            long startTime = System.currentTimeMillis();
            byte[] buffer = new byte[1024];
            DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);

            while (System.currentTimeMillis() - startTime < 1000) {
                Log.e(TAG, "111111111111111111: " );
                try {
                    //有问题
                    socket.receive(responsePacket);
                    handleResponse(responsePacket);
                } catch (SocketTimeoutException e) {
                    Log.e(TAG, "Socket timeout: No response received within the timeout period", e);
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error in sendBroadcast", e);
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }

    private void handleResponse(DatagramPacket responsePacket) {
        String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
        String serverIp = responsePacket.getAddress().getHostAddress();
        Log.d(TAG, "Received response from: " + serverIp+":"+response);

        if ("YES".equals(response)) {
            navigateToChatActivity(serverIp);
        } else if (!"NO".equals(response)) {
            processUserResponse(response);
        }
    }

    private void navigateToChatActivity(String serverIp) {
        new Handler(Looper.getMainLooper()).post(() -> {
            Intent intent = new Intent(binding.getRoot().getContext(), OnlineChatActivity.class);
            intent.putExtra("identity", "service");
            intent.putExtra("serverAddress", serverIp);
            startActivity(intent);

            String tableName = "t" + serverIp.replace(".", "");
            groupRepository.insertGroup(tableName,userClass.getUsername(),userClass.getUserIp());
        });
    }

    private void processUserResponse(String response) {
        UserRepository.User user = gson.fromJson(response, UserRepository.User.class);
        if (user == null) {
            Log.e(TAG, "Parsed user is null");
            return;
        }

        new Handler(Looper.getMainLooper()).post(() -> {
            boolean isContain = false;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                if (list != null && list.size() != 0) {
                    isContain = list.stream()
                            .anyMatch(u -> u.getUserIp().equals(user.getUserIp()));
                }
                if (!isContain) {
                    isContain = user.getUserIp().equals(localIpAddress);
                }

            }

            if (!isContain) {
                list.add(user);
                adapter.notifyDataSetChanged(); // 更新适配器
            }
        });

    }

    private void showToast(final String message) {
        new Handler(Looper.getMainLooper()).post(() -> {
            if (getContext() != null && message != null && !message.isEmpty()) {
                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "Cannot show toast.");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        executorService.shutdownNow(); // 关闭 ExecutorService 并中断所有任务
    }

    public static String getLocalIpAddress(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();

            if (ipAddress != 0) {
                return String.format("%d.%d.%d.%d",
                        (ipAddress & 0xff),
                        (ipAddress >> 8 & 0xff),
                        (ipAddress >> 16 & 0xff),
                        (ipAddress >> 24 & 0xff));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
